package cn.javaxc.mvcwork.framework.mybatis;

import java.lang.reflect.Field;
import java.sql.*;
import java.util.List;
import java.util.*;


import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import cn.javaxc.mvcwork.util.common.DatabaseUtils;
import cn.javaxc.mvcwork.controller.MVCConfig;
import cn.javaxc.mvcwork.util.helper.ReflectHelper;
import cn.javaxc.mvcwork.controller.web.PagedListInfo;

@Intercepts({@Signature(type=StatementHandler.class,method="update",args={Statement.class})})
public class InsertPlugin implements Interceptor {


	
	public Object intercept(Invocation ivk) throws Throwable {
		Object ret=ivk.proceed();
		// TODO Auto-generated method stub
		if(ivk.getTarget() instanceof StatementHandler){
			StatementHandler statementHandler = (StatementHandler)ivk.getTarget();
			ParameterHandler parameterHandler = statementHandler.getParameterHandler();
//			BaseStatementHandler delegate = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
//			StatementHandler delegate = (StatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
			MappedStatement mappedStatement = (MappedStatement) ReflectHelper.getValueByFieldName(parameterHandler, "mappedStatement");
			Statement emt = (Statement) ivk.getArgs()[0];
			if (mappedStatement.getKeyProperties()!=null){
				return DatabaseUtils.getCurrVal(emt.getConnection(),"",-1);
//				for (String key:mappedStatement.getKeyProperties()){
//					if(parameterHandler.getParameterObject() instanceof Map){
//						return ((Map)parameterHandler.getParameterObject()).get(key);
//					}
//				}
			}
		}
		return ret;
	}


	
	public Object plugin(Object arg) {
		// TODO Auto-generated method stub
		return Plugin.wrap(arg, this);
	}	
	public void setProperties(Properties p) {

	}

}
